from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from goods.models import GoodsChannel, GoodsChannelGroup, GoodsCategory
from meiduo_admin.serializers.channels import GoodsChannelSerializer, GoodsChannelGroupSerializer
from meiduo_admin.serializers.spus import GoodsCategorySerializers
from meiduo_admin.utils import PageNum, ChannelPermission


class ChannelsView(ModelViewSet):
    serializer_class =GoodsChannelSerializer
    queryset = GoodsChannel.objects.all()
    pagination_class = PageNum
    permission_classes = [IsAdminUser]
    permission_classes_by_action = {'create': [ChannelPermission],
                                    'update': [ChannelPermission],
                                    'destroy': [ChannelPermission]
                                    }

    def get_permissions(self):
        try:
            # return permission_classes depending on `action`
            return [permission() for permission in self.permission_classes_by_action[self.action]]
        except KeyError:
            # action is not set return default permission_classes
            return [permission() for permission in self.permission_classes]

    def channel_types(self,request):
        channel_groups = GoodsChannelGroup.objects.all()
        ser = GoodsChannelGroupSerializer(channel_groups,many=True)
        return Response(ser.data)
    def categories(self,request):
        categories = GoodsCategory.objects.filter(parent=None)
        ser = GoodsCategorySerializers(categories, many=True)
        return Response(ser.data)